import 'package:common/export/bloc.dart';
import 'package:cms/api/single.dart';
import 'package:cms/models/single.dart';
import 'package:common/dio/model.dart';
import 'package:common/export/get_it.dart';
import 'package:components/pull_down_refresh/controller.dart';
import 'package:common/utils/lara_press_verify.dart';
import 'package:user/state/user_action_history/user_action_history_cubit.dart';
import 'list_state.dart';

class ListCubit extends Cubit<ListState> {
  final int categoryId;
  final String searchKeyword;
  ListCubit({this.categoryId = 0, this.searchKeyword = ''})
    : super(ListState.initial()) {
    state.refreshController = LaraPressRefreshController();
    getList();
  }

  Future<void> getList({bool isRefresh = false}) async {
    try {
      Map<String, dynamic> params = {};
      if (categoryId != 0) {
        params['cat'] = categoryId;
      }
      if (!LaraPressVerify.isEmpty(searchKeyword)) {
        params['s'] = searchKeyword;
      }
      LarapressPaginatedResponse<SingleModel> response =
          await LaraPressSingleApi().list(params);
      emit(state.copyWith(list: response.data));
      if (isRefresh) {
        state.refreshController.refreshCompleted();
      }
      // 如果搜索关键词不为空，且有数据，则添加搜索记录
      if (!LaraPressVerify.isEmpty(searchKeyword) &&
          response.data?.isNotEmpty == true) {
        LaraPressUserActionHistoryCubit actionHistoryCubit =
            laraPressGetIt<LaraPressUserActionHistoryCubit>();
        actionHistoryCubit.addSearchHistory(searchKeyword);
      }
    } catch (e) {
      emit(state.copyWith(list: []));
    } finally {
      emit(state.copyWith(isLoading: false));
    }
  }
}
